window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');

  let gl = getWebGLContext(canvas, false);
  initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  canvas.addEventListener('click', e => {
    let x = (e.x - canvas.offsetLeft - canvas.width * 0.5) / (canvas.width * 0.5);
    let y = (canvas.height * 0.5 - e.y + canvas.offsetTop) / (canvas.height * 0.5);
    drawPoints(gl, [x, y, 1.0, 1.0]);
  });
});

// 定点着色器
// a_Position.x
const VSHADER_SOURCE = `
attribute vec4 a_Position;
uniform mat4 u_xformMatrix;
void main(){
    gl_Position = u_xformMatrix*a_Position;
}`;

const FSHADER_SOURCE = `
precision mediump float;
uniform vec4 u_FragColor;
void main(){
    gl_FragColor = u_FragColor;
}
`;

/**
 *
 * @param {Object} gl
 * @param {Array} positions length=4
 */
const points = [];
const drawPoints = (gl, positions = [0.0, 0.0, 0.0, 1.0]) => {
  gl.clear(gl.COLOR_BUFFER_BIT);

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  let u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
  let u_xformMatrix = gl.getUniformLocation(gl.program, 'u_xformMatrix');

  points.push(...positions);
  if (points.length / 4 < 3) return;
  gl.uniform4f(u_FragColor, 1, 0, 0, 1);
  // gl.uniformMatrix4fv(u_xformMatrix, false, rotationMatrix(90));
  let xformMatrix = new Matrix4();
  xformMatrix.setRotate(90, 0, 0, 1);
  gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix.elements);

  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(points), gl.STATIC_DRAW);
  gl.vertexAttribPointer(a_Position, 4, gl.FLOAT, false, 0, 0);
  gl.enableVertexAttribArray(a_Position);

  gl.drawArrays(gl.TRIANGLE_STRIP, 0, points.length / 4);
};

const rotationMatrix = angle => {
  let temp = angle / 180 * Math.PI;
  return new Float32Array([
    Math.cos(temp), Math.sin(temp), 0.0, 0.0, -Math.sin(temp), Math.cos(temp), 0.0, 0.0,
    0.0, 0.0, 0.0, 1.0,
    0.0, 0.0, 0.0, 1.0
  ]);
};